import { app, shell, BrowserWindow, ipcMain, session, Menu, MenuItemConstructorOptions } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import Store from 'electron-store'
import logger from './util/Log'
import { saveRequest, loadRequests, deleteRequest, updateRequest } from './database'
import axios from 'axios'

interface StoreType {
  [key: string]: any
}

const store = new Store<StoreType>()

// 将 mainWindow 声明为全局变量
let mainWindow: BrowserWindow | null = null

// 修改菜单模板定义
const template: MenuItemConstructorOptions[] = [
  {
    label: '主页',
    click: async () => {
      mainWindow?.webContents.send('open-main')
    }
  },
  {
    label: '设置',
    click: async () => {
      mainWindow?.webContents.send('open-settings')
    }
  },
  {
    label: '关于',
    click: async () => {
      mainWindow?.webContents.send('open-about')
    }
  }
]

function createWindow(): void {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 670,
    show: false,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.mjs'),
      sandbox: false,
      webSecurity: is.dev ? false : true
    }
  })


  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // 创建菜单
  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

function initIpcRenderer() {
  ipcMain.on('setStore', (_, key, value) => {
    store.set(key, value)
  })

  ipcMain.on('getStore', (_, key) => {
    let value = store.get(key)
    _.returnValue = value || null
  })

  ipcMain.on('removeStore', (_, key) => {
    store.delete(key)
  })

  ipcMain.on('clearStore', () => {
    store.clear()
  })
  ipcMain.on('logger', (_, level, tag, message) => {
    switch (level) {
      case 0:
        logger.trace(`[${tag}] ${message}`)
        break
      case 1:
        logger.debug(`[${tag}] ${message}`)
        break
      case 2:
        logger.info(`[${tag}] ${message}`)
        break
      case 3:
        logger.warn(`[${tag}] ${message}`)
        break
      case 4:
        logger.error(`[${tag}] ${message}`)
        break
      default:
        break
    }
  })

  // 添加获取版本号的 IPC 处理
  ipcMain.handle('get-app-version', (): string => {
    return app.getVersion()
  })

  // 添加检查更新的 IPC 处理
  ipcMain.handle('check-update', async (): Promise<{hasUpdate: boolean; latestVersion: string}> => {
    console.log('check-update')
    try {
      const response = await axios.get('https://gitee.com/api/v5/repos/allen056/electron-vite-naive/releases/latest')
      console.log(response.data)
      const latestVersion = response.data.tag_name.replace('v', '')
      const currentVersion = app.getVersion()
      // 比较版本号
      const hasUpdate = compareVersions(latestVersion, currentVersion) > 0
      
      return {
        hasUpdate,
        latestVersion
      }
    } catch (error) {
      console.error('Check update failed:', error)
      throw error
    }
  })
}

// 添加版本号比较函数
function compareVersions(v1: string, v2: string): number {
  const v1Parts = v1.split('.').map(Number)
  const v2Parts = v2.split('.').map(Number)
  
  for (let i = 0; i < 3; i++) {
    if (v1Parts[i] > v2Parts[i]) return 1
    if (v1Parts[i] < v2Parts[i]) return -1
  }
  
  return 0
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
  // IPC test
  ipcMain.on('ping', () => console.log('pong'))
  createWindow()
  initIpcRenderer()
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.

// 注册 IPC 处理程序
ipcMain.handle('save-http-request', async (_, data) => {
  return await saveRequest(data)
})

ipcMain.handle('load-http-requests', async () => {
  return await loadRequests()
})

ipcMain.handle('delete-http-request', async (_, id) => {
  return await deleteRequest(id)
})

ipcMain.handle('update-http-request', async (_, data) => {
  return await updateRequest(data)
})

ipcMain.on('open-external-url', (_event, url) => {
  shell.openExternal(url)
})

ipcMain.handle('proxy-http-request', async (_, config) => {
  try {
    const response = await axios(config)
    return {
      data: response.data,
      status: response.status,
      headers: response.headers,
      success: true
    }
  } catch (error) {
    return {
      success: false,
      error: {
        message: error.message,
        response: error.response?.data
      }
    }
  }
})
